<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 公共接口
 */
class Ai extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function send(){
        $message = $this->request->post('message');
        $type = $this->request->post('type',1);// 1:普通聊天 2：检测报告单项聊天 3：检测报告整体聊天
        $order_id = $this->request->post('order_id');
        $report_id = $this->request->post('report_id');// 检测报告id
        $report = $this->request->post('report/a',null);// 检测报告

        if($type == 1){
            if (!$message) {
                $this->error('请输入内容');
            }
            $message = $this->message1($message,$order_id);
        }else if( $type == 2){
            if (!$report_id) {
                $this->error('请输入报告信息');
            } 
            $message = $this->message2($message,$report_id,$report);
        }else if( $type == 3){
            if (!$order_id) {
                $this->error('请输入订单信息');
            }
            $message = $this->message1($message ?? '分析下报告内容',$order_id);
        }

        $res = (new \app\api\library\Ai())->send($message);
        if($res){
             $this->success('成功',$res['choices'][0]['message']);
        }else{
            $this->error('请稍后再试');
        }
       

    }

    public function message1($message,$order_id){
        $template = null;
        if($order_id){
            $order = \app\api\model\order\OrderMaster::where('id',$order_id)->find();
            $list = \app\api\model\order\OrderReport::where('order_id',$order_id)->select();
            $template = "患者信息: \n姓名: {$order->username}\n年龄: {$order->age}\n性别: {$order->gender}\n报告列表: \n";
            foreach ($list as $key => $value) {
                
                $template .= json_encode($value->report_content)."\n";
            }
        }
        $template .= "患者提问: \n{$message}\n";
        return $template;
    }


    public function message2($message,$report_id,$report){
        $template = null;
        $model = \app\api\model\order\OrderReport::where('id',$report_id)->find();
        $order = \app\api\model\order\OrderMaster::where('id',$model->order_id)->find();
        $template = "患者信息: \n姓名: {$order['username']}\n年龄: {$order['age']}\n性别: {$order['gender']}\n报告列表: \n";
        $report_content = json_encode($model->report_content);
        $template .= $report_content."\n";
        $message = $message ?? '这项数据代表含义';
        $template .= "患者提问: {$message}\n";
        if($report){
            $template .= "‘{$report['checkItem_name']}为{$report['report_result']}{$report['Unit']}参考范围{$report['ranges']}’\n";
        }
        return $template;
    }

}